package tech.aistar.controller;


import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tech.aistar.dto.CheckQues;
import tech.aistar.dto.Wrong;
import tech.aistar.entity.*;
import tech.aistar.service.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
@RequestMapping("/parper")
public class WrongtopicAction {
    //试卷库
    @Autowired
    private IParperBankService parperBankService;
    //试卷中间库
    @Autowired
    private IQuestionpaperService questionpaperService;
    //错题库
    @Autowired
    public IWrongtopicService wrongtopicService;
    //成绩库
    @Autowired
    public IExaScoreService exaScoreService;
    //试卷时间表
    @Autowired
    private IExaInfoService exaInfoService;
    //单选
    @Autowired
    public ISinchoiceService sinchoiceService;
    //多选
    @Autowired
    public IManchoiceService manchoiceService;
    //填空
    @Autowired
    public ICompletionService completionService;
    //编程
    @Autowired
    public IProgrammingService programmingService;


    @RequestMapping("/wrongtopicadd")
    @ResponseBody
    public Integer Wrongtopicadd(HttpServletRequest req, HttpSession session){
        User user = (User) session.getAttribute("user");
        Long usId = user.getUsId();//用户id
        String json = req.getParameter("checkQues");//接收request作用域中的数据    json字符串格式
        //将json字符串格式的数据转化为json字符数组格式    CheckQues.class是数组里面的数据是CheckQues类型
        List<CheckQues> checkQues = JSON.parseArray(json, CheckQues.class);

        Wrongtopic wrongtopic = new Wrongtopic();
        Integer data = 0; //这个是要返回到前端添加返回的结果,是否成功
        for(int i = 0; i < checkQues.size(); i++){
            //如果是单选题
            if (checkQues.get(i).getQueType() == 1){
                System.out.println("单选题" + i);
                Long sinId =  checkQues.get(i).getQueId();//用户提交的单选题id
                String answerByid = sinchoiceService.findAnswerByid(sinId);//通过id找到答案
                String answer = checkQues.get(i).getAnswer();//用户的答案
                if (!answerByid.equals(answer)){//答案不正确

                    wrongtopic.setTestId(checkQues.get(i).getTestId());//考试号
                    wrongtopic.setWrongParperId(checkQues.get(i).getParperId());//试卷号
                    wrongtopic.setWrongType(checkQues.get(i).getQueType());//题目类型
                    wrongtopic.setWrongQid(checkQues.get(i).getQueId());//题目id
                    wrongtopic.setWrongUid(usId); //用户Id
                    wrongtopic.setWrongAnswer(checkQues.get(i).getAnswer());//用户答案
                    Integer i1 = wrongtopicService.insertWrongtopic(wrongtopic);//插入数据库
                    data = i1;
                }
            }
            //如果是多选题
            if (checkQues.get(i).getQueType() == 2){
                System.out.println("多选题");
                Long sinId =  checkQues.get(i).getQueId();//用户提交的多选题id
                String answerByid = manchoiceService.findAnswerByid(sinId);//通过id找到正确答案
                String answer = checkQues.get(i).getAnswer();//用户的答案
                if (!answerByid.equals(answer)){//答案不正确
                    wrongtopic.setTestId(checkQues.get(i).getTestId());//考试号
                    wrongtopic.setWrongParperId(checkQues.get(i).getParperId());//试卷号
                    wrongtopic.setWrongType(checkQues.get(i).getQueType());//题目类型
                    wrongtopic.setWrongQid(checkQues.get(i).getQueId());//题目id
                    wrongtopic.setWrongUid(usId); //用户Id
                    wrongtopic.setWrongAnswer(checkQues.get(i).getAnswer());//用户答案
                    Integer i1 = wrongtopicService.insertWrongtopic(wrongtopic);//插入数据库
                    data = i1;

                }
            }
            //如果是填空题
            if (checkQues.get(i).getQueType() == 3){
                System.out.println("填空题");
                Long sinId =  checkQues.get(i).getQueId();//用户提交的多选题id
                String answerByid = completionService.findAnswerByid(sinId);//通过id找到正确答案
                String answer = checkQues.get(i).getAnswer();//用户的答案
                if (!answerByid.equals(answer)){//答案不正确
                    wrongtopic.setTestId(checkQues.get(i).getTestId());//考试号
                    wrongtopic.setWrongParperId(checkQues.get(i).getParperId());//试卷号
                    wrongtopic.setWrongType(checkQues.get(i).getQueType());//题目类型
                    wrongtopic.setWrongQid(checkQues.get(i).getQueId());//题目id
                    wrongtopic.setWrongUid(usId); //用户Id
                    wrongtopic.setWrongAnswer(checkQues.get(i).getAnswer());//用户答案

                    Integer i1 = wrongtopicService.insertWrongtopic(wrongtopic);//插入数据库
                    data = i1;

                }
            }
            //如果是编程题
            if (checkQues.get(i).getQueType() == 4){
                System.out.println("编程题");
                Long sinId =  checkQues.get(i).getQueId();//用户提交的多选题id
                String answerByid = programmingService.findAnswerByid(sinId);//通过id找到正确答案
                String answer = checkQues.get(i).getAnswer();//用户的答案
                if (!answerByid.equals(answer)){//答案不正确
                    wrongtopic.setTestId(checkQues.get(i).getTestId());//考试号
                    wrongtopic.setWrongParperId(checkQues.get(i).getParperId());//试卷号
                    wrongtopic.setWrongType(checkQues.get(i).getQueType());//题目类型
                    wrongtopic.setWrongQid(checkQues.get(i).getQueId());//题目id
                    wrongtopic.setWrongUid(usId); //用户Id
                    wrongtopic.setWrongAnswer(checkQues.get(i).getAnswer());//用户答案
                    Integer i1 = wrongtopicService.insertWrongtopic(wrongtopic);//插入数据库
                    data = i1;
                }
            }
        }
        return data;
    }

    @RequestMapping("/wrong/{testId}")
    public String Wrong(Model model ,@PathVariable("testId") Long testId,HttpSession session){
        User user = (User) session.getAttribute("user");
        Long usId = user.getUsId();//用户id
        List<Wrongtopic> byTestId = wrongtopicService.findByTestId(testId, usId);//查询错题库
        Long parperId = byTestId.get(0).getWrongParperId();//试卷号
        Long sin = questionpaperService.countType(parperId, 1L);//单选题的个数
        Long man = questionpaperService.countType(parperId, 2L);//多选题的个数
        Long cmo = questionpaperService.countType(parperId, 3L);//填空
        Long pro = questionpaperService.countType(parperId, 4L);//编程
        Long queNumber = sin + man + cmo + pro ;//总共题数
        Long totalScore = (pro * 20 + cmo * 5 + man * 5 + sin * 5);//总分
        /**
         * 下面是把错题数据写入要传到前端的集合
         */
        List<Wrong> wrongList = new ArrayList<>();//传回前端的集合
        for(int i = 0; i < byTestId.size(); i++){
            Long wrongType = byTestId.get(i).getWrongType();//错题类型
            Long wrongQid = byTestId.get(i).getWrongQid();//错题编号
            String wrongAnswer = byTestId.get(i).getWrongAnswer();//用户答案
            //如果是单选题
            if (wrongType == 1L){
                Sinchoice sinchoice = sinchoiceService.findById(wrongQid);
                Wrong wrong = new Wrong();
                wrong.setQueNumber(queNumber);//总共题数
                wrong.setTotalScore(totalScore);//总分
                wrong.setWrongType("单选题");//题目类型
                wrong.setWrongStem(sinchoice.getSinStem());//题目内容
                wrong.setWrongAnswer(wrongAnswer);//用户答案
                wrong.setTrueAnswer(sinchoice.getSinAnswer());//正确答案
                wrongList.add(wrong);
            }
            //如果是多选题
            else if (wrongType == 2L){
                Manchoice manchoice = manchoiceService.findById(wrongQid);
                Wrong wrong = new Wrong();
                wrong.setQueNumber(queNumber);
                wrong.setTotalScore(totalScore);
                wrong.setWrongType("多选题");//题目类型
                wrong.setWrongStem(manchoice.getManStem());//题目内容
                wrong.setWrongAnswer(wrongAnswer);//用户答案
                wrong.setTrueAnswer(manchoice.getManAnswer());//正确答案
                wrongList.add(wrong);
            }
            //如果是填空题
            else if (wrongType == 3L){
                Completion completion = completionService.findById(wrongQid);
                Wrong wrong = new Wrong();
                wrong.setQueNumber(queNumber);
                wrong.setTotalScore(totalScore);
                wrong.setWrongType("填空题");//题目类型
                wrong.setWrongStem(completion.getComStem());//题目内容
                wrong.setWrongAnswer(wrongAnswer);//用户答案
                wrong.setTrueAnswer(completion.getComAnswer());//正确答案
                wrongList.add(wrong);
            }
            //如果是编程题
            else if (wrongType == 4L){
                Programming programming= programmingService.findById(wrongQid);
                Wrong wrong = new Wrong();
                wrong.setQueNumber(queNumber);
                wrong.setTotalScore(totalScore);
//                wrong.setParperid(parperId);//试卷编号
                wrong.setWrongType("编程题");//题目类型
                wrong.setWrongStem(programming.getProStem());//题目内容
                wrong.setWrongAnswer(wrongAnswer);//用户答案
                wrong.setTrueAnswer(programming.getProAnswer());//正确答案
                wrongList.add(wrong);
            }
        }

        /**
         * 下面是ExaScore的相关操作
         */
        Long scorce = 0L;//错了多少分
        for (int i =0; i < wrongList.size(); i++){
            if (wrongList.get(i).getWrongType() == "编程题"){
                scorce = scorce + 20;
            }
            else{
                scorce = scorce + 5;
            }
        }
        System.out.println("scorce"+scorce);
        Integer Usescorce = Math.toIntExact(totalScore - scorce);//得分

        Calendar calendar = Calendar.getInstance();//获取现在时间
        Date time=calendar.getTime();//获取毫秒数
        long nowTime = time.getTime();
        ExaInfo exaInfo = exaInfoService.findexa(String.valueOf(testId));
        Date testStart = exaInfo.getTestStart();//开始考试时间
        long time1 = testStart.getTime();
        Long timeLen =  nowTime - time1; //考试用时
        System.out.println(timeLen);
        //将long时间转成String型
        timeLen =  timeLen / 1000;
        Long hour =timeLen / 3600;//小时
        timeLen %= 3600;//小时后余下的秒数
        Long minute  = timeLen / 60;//分钟
        timeLen %= 60;//余下秒数
        Long second  = timeLen;//秒
        String str = hour + ":" + minute + ":" + second;
        System.out.println("strstrstrstrstrstrstrstrstrstrstrstr"+str);

        ExaScore exaScore = new ExaScore();
        exaScore.setExaScore(Usescorce);
        exaScore.setTestId(testId);
        exaScore.setUsId(usId);
        exaScore.setExaTime(str);
        System.out.println("exaScoreexaScoreexaScoreexaScoreexaScore"+exaScore);
        Integer integer = exaScoreService.insertExaScore(exaScore);//添加到成绩表
        System.out.println("exaScoreexaScoreexaScoreexaScoreexaScoreexaScoreexaScore"+integer);

        /**
         * 下面是parperBank操作.更新使用次数
         */
        Long parperCount = parperBankService.findCount(parperId);
        parperCount++;
        Integer integer1 = parperBankService.updateBank(parperCount,parperId);
        model.addAttribute("wrongList", JSON.toJSON(wrongList));
        return "wrong";
    }
}
